package cn.jinhe.doc.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jinhe.doc.base.DaoSupportImpl;
import cn.jinhe.doc.domain.PageBean;
import cn.jinhe.doc.domain.Repository;
import cn.jinhe.doc.domain.Topic;
import cn.jinhe.doc.service.TopicService;
@Service
@Transactional
@SuppressWarnings("unchecked")
public class TopicServiceImpl extends DaoSupportImpl<Topic> implements TopicService{

	@Deprecated
	public List<Topic> findByRepository(Repository repository) {
		
		return getSession().createQuery(//
				"FROM Topic t WHERE t.repository=? ORDER BY (CASE t.type WHEN 2 THEN 2 ELSE 0 END) DESC,  t.lastUpdateTime DESC")//
				.setParameter(0, repository)
				.list();
	}

	public void save(Topic topic)
	{
		//1、设置属性并保存
		topic.setType(Topic.TYPE_NORMAL);//默认为一般文章
		topic.setLastReply(null);
		topic.setReplyCount(0);
		topic.setLastUpdateTime(topic.getPostTime());
		 
		 getSession().save(topic);
		 //2、维护特殊属性
		 Repository repository=topic.getRepository();
		 repository.setTopicCount(repository.getTopicCount()+1);  //主题数量
		 repository.setArticleCount(repository.getArticleCount()+1);//文章数量
		 repository.setLastTopic(topic);//最后发表主题
		 
		 getSession().save(repository);
				 
	}


	public PageBean getPageBeanByRepository(int pageNum, int pageSize, Repository repository) {

		// 查询本页的数据列表
		List list = getSession().createQuery(//
				"FROM Topic t WHERE t.repository=? ORDER BY (CASE t.type WHEN 2 THEN 2 ELSE 0 END) DESC, t.lastUpdateTime DESC")//
				.setParameter(0, repository)//
				.setFirstResult((pageNum - 1) * pageSize)//
				.setMaxResults(pageSize)//
				.list();

		// 查询总记录数量
		Long count = (Long) getSession().createQuery(//
				"SELECT COUNT(*) FROM Topic t WHERE t.repository=?")//
				.setParameter(0, repository)//
				.uniqueResult();

		return new PageBean(pageNum, pageSize, list,count.intValue());
	}

}
